package cn.dwong.msgGateway.service;

import cn.dwong.msgGateway.base.ApiResponse;
import cn.dwong.msgGateway.base.LoginApiResponse;
import cn.dwong.msgGateway.entity.User;
import cn.dwong.msgGateway.entity.UserLogoutInfo;
import cn.dwong.msgGateway.util.SingletonCacheUtil;
import cn.hutool.cache.Cache;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author 73202
 * @date 2022/3/9 17:46
 */
@Service
public class UserService {
    private final Logger log = LoggerFactory.getLogger(UserService.class);
    Cache<Object, Object> userCache = new SingletonCacheUtil().getSingletonCacheUtil();

    public void register(User user){
        userCache.put(user.getUserName(),user.getPassword());
//        log.info("用户注册成功：用户名是 {}，密码是 {}",user.getUserName(),userCache.get(user.getUserName()));
    }

    public boolean login(User user){
        if(user.getPassword().equals(userCache.get(user.getUserName()))){
            //生成sessionId
            String sessionKey = user.getUserName()+user.getPassword();
            if(userCache.get(sessionKey) == null){
                String sessionId = IdUtil.randomUUID();
                userCache.put(sessionKey,sessionId);
            }
            return true;
        }
        return false;
    }

    public String getSessionId(User user)  {
        return userCache.get(user.getUserName()+user.getPassword()).toString();
    }

    public boolean logout(UserLogoutInfo logoutInfo){
        //注销，移除sessionId
        if (userCache.get(logoutInfo.getUserName()) != null){
            String password = userCache.get(logoutInfo.getUserName()).toString();
            String sessionKey = logoutInfo.getUserName()+password;
            Object sessionId = userCache.get(sessionKey);
            if (sessionId != null){
                if (logoutInfo.getSessionId().equals(sessionId.toString())){
                    userCache.remove(sessionKey);
                    return true;
                }
            }
        }

        return false;
    }
}
